package com.example.ad.sdk.domain.utils

import android.app.ActivityManager
import android.content.Context
import android.content.pm.PackageInfo
import android.os.Build
import android.os.Process
import com.example.ad.sdk.domain.helper.ContextHelper

object AppInfoUtil {

    fun getVersionCode(): Int {
        var appVersionCode: Long = 0
        try {
            val packageInfo: PackageInfo = ContextHelper.context.applicationContext
                .packageManager
                .getPackageInfo(ContextHelper.context.packageName, 0)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                appVersionCode = packageInfo.longVersionCode
            } else {
                appVersionCode = packageInfo.versionCode.toLong()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return appVersionCode.toString().toInt()
    }

    fun getPackageName(): String{
        var packageName = ContextHelper.context.packageName
        try {
            val packageInfo: PackageInfo = ContextHelper.context.applicationContext
                .packageManager
                .getPackageInfo(ContextHelper.context.packageName, 0)
            packageName = packageInfo.packageName
        } catch (e: Exception) {
            e.printStackTrace()
        }
        if (packageName.isEmpty()){
            return getProcessName()
        }

        return packageName
    }

    fun getProcessName(): String {
        val manager =  ContextHelper.context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (processInfo in manager.runningAppProcesses) {
            if (processInfo.pid == Process.myPid()) {
                return processInfo.processName
            }
        }
        return  ""
    }
}